use rustcloud_core::{Request, Response, ServiceInstance, ServiceRegistry, LoadBalancerStrategy};
use rustcloud_registry::InMemoryRegistry;
use rustcloud_loadbalancer::LoadBalancerManager;
use rustcloud_transport::HttpTransport;
use rustcloud_proxy::ServiceProxy;
use rustcloud_resilience::{RetryExecutor, RetryConfig, CircuitBreaker, CircuitBreakerConfig, BackoffStrategy};
use rustcloud_observability::{HealthCheckManager, MetricsCollector, AlertManager};
use rustcloud_bus::memory::InMemoryMessageBus;
use rustcloud_stream::{BusStreamSource, BusStreamSink, MapProcessor, FilterProcessor};
use rustcloud_admin::{ServiceDiscovery, LoadBalancerConfig};

use std::sync::Arc;
use std::time::Duration;
use serde_json::json;

/// API兼容性验证测试
/// 确保所有公共API保持向后兼容性
#[tokio::test]
async fn test_api_compatibility() {
    println!("🔍 开始API兼容性验证...");
    
    // 1. 核心模块API兼容性验证
    test_core_api_compatibility().await;
    
    // 2. 注册中心API兼容性验证
    test_registry_api_compatibility().await;
    
    // 3. 负载均衡API兼容性验证
    test_loadbalancer_api_compatibility().await;
    
    // 4. 传输层API兼容性验证
    test_transport_api_compatibility().await;
    
    // 5. 代理服务API兼容性验证
    test_proxy_api_compatibility().await;
    
    // 6. 容错机制API兼容性验证
    test_resilience_api_compatibility().await;
    
    // 7. 可观测性API兼容性验证
    test_observability_api_compatibility().await;
    
    // 8. 消息总线API兼容性验证
    test_bus_api_compatibility().await;
    
    // 9. 流处理API兼容性验证
    test_stream_api_compatibility().await;
    
    // 10. 管理模块API兼容性验证
    test_admin_api_compatibility().await;
    
    println!("✅ 所有API兼容性验证通过！");
}

async fn test_core_api_compatibility() {
    println!("  📋 验证rustcloud-core API兼容性...");
    
    // 验证Request API
    let mut request = Request::new("test-service", "GET", "/api/test");
    request.set_body(b"test body".to_vec());
    request.add_header("Content-Type", "application/json");
    
    assert_eq!(request.service_name(), "test-service");
    assert_eq!(request.method(), "GET");
    assert_eq!(request.path(), "/api/test");
    assert!(request.body().is_some());
    assert!(request.headers().contains_key("Content-Type"));
    
    // 验证Response API
    let mut response = Response::new(200);
    response.set_body(b"response body".to_vec());
    response.add_header("Server", "RustCloud");
    
    assert_eq!(response.status, 200);
    assert!(response.body.is_some());
    assert!(response.headers.contains_key("Server"));
    
    // 验证ServiceInstance API
    let instance = ServiceInstance::new("api-service", "localhost", 8080, "http");
    assert_eq!(instance.service_name(), "api-service");
    assert_eq!(instance.host(), "localhost");
    assert_eq!(instance.port(), 8080);
    assert_eq!(instance.protocol(), "http");
    
    println!("    ✓ rustcloud-core API兼容性验证通过");
}

async fn test_registry_api_compatibility() {
    println!("  📋 验证rustcloud-registry API兼容性...");
    
    let registry = Arc::new(InMemoryRegistry::new());
    let instance = ServiceInstance::new("test-service", "localhost", 8080, "http");
    
    // 验证基础注册API
    registry.register(instance.clone()).await.unwrap();
    let instances = registry.discover("test-service").await.unwrap();
    assert!(!instances.is_empty());
    
    registry.deregister(&instance).await.unwrap();
    let instances_after = registry.discover("test-service").await.unwrap();
    assert!(instances_after.is_empty());
    
    println!("    ✓ rustcloud-registry API兼容性验证通过");
}

async fn test_loadbalancer_api_compatibility() {
    println!("  📋 验证rustcloud-loadbalancer API兼容性...");
    
    // 验证负载均衡策略
    let lb_manager = LoadBalancerManager::new(LoadBalancerStrategy::RoundRobin);
    
    let instances = vec![
        ServiceInstance::new("service", "host1", 8080, "http"),
        ServiceInstance::new("service", "host2", 8080, "http"),
    ];
    
    let selected = lb_manager.select(&instances).unwrap();
    assert!(instances.contains(&selected));
    
    println!("    ✓ rustcloud-loadbalancer API兼容性验证通过");
}

async fn test_transport_api_compatibility() {
    println!("  📋 验证rustcloud-transport API兼容性...");
    
    let transport = HttpTransport::new();
    
    // 验证传输配置
    let config = rustcloud_core::TransportConfig::default();
    assert!(config.timeout > Duration::from_secs(0));
    
    println!("    ✓ rustcloud-transport API兼容性验证通过");
}

async fn test_proxy_api_compatibility() {
    println!("  📋 验证rustcloud-proxy API兼容性...");
    
    let registry = Arc::new(InMemoryRegistry::new());
    let load_balancer = Arc::new(LoadBalancerManager::new(LoadBalancerStrategy::RoundRobin));
    let transport = Arc::new(HttpTransport::new());
    let circuit_breaker = Arc::new(rustcloud_circuit_breaker::DefaultCircuitBreaker::new(
        rustcloud_circuit_breaker::CircuitBreakerConfig::default()
    ));
    
    // 验证ServiceProxy构造函数API
    let _proxy = ServiceProxy::new(registry, load_balancer, transport, circuit_breaker);
    
    println!("    ✓ rustcloud-proxy API兼容性验证通过");
}

async fn test_resilience_api_compatibility() {
    println!("  📋 验证rustcloud-resilience API兼容性...");
    
    // 验证重试执行器API
    let retry_config = RetryConfig {
        max_attempts: 3,
        timeout: Duration::from_secs(5),
        backoff: BackoffStrategy::Fixed {
            delay: Duration::from_millis(100),
        },
        retry_conditions: vec![],
        budget_percent: 10.0,
        jitter_enabled: true,
    };
    
    let _retry_executor = RetryExecutor::new(retry_config);
    
    // 验证熔断器API
    let circuit_config = CircuitBreakerConfig::default();
    let _circuit_breaker = CircuitBreaker::new(circuit_config);
    
    println!("    ✓ rustcloud-resilience API兼容性验证通过");
}

async fn test_observability_api_compatibility() {
    println!("  📋 验证rustcloud-observability API兼容性...");
    
    // 验证健康检查管理器API
    let health_manager = HealthCheckManager::new();
    assert!(health_manager.check_health().await.is_ok());
    
    // 验证指标收集器API
    let metrics_collector = MetricsCollector::new();
    metrics_collector.record_counter("test.counter", 1.0, vec![]).await;
    metrics_collector.record_histogram("test.histogram", 100.0, vec![]).await;
    
    let metrics = metrics_collector.get_metrics().await;
    assert!(!metrics.is_empty());
    
    // 验证告警管理器API
    let _alert_manager = AlertManager::new();
    
    println!("    ✓ rustcloud-observability API兼容性验证通过");
}

async fn test_bus_api_compatibility() {
    println!("  📋 验证rustcloud-bus API兼容性...");
    
    let bus = InMemoryMessageBus::new().await.unwrap();
    
    // 验证发布者API
    let publisher = bus.create_publisher().unwrap();
    
    let message = rustcloud_bus::prelude::MessageBuilder::new()
        .topic("test.topic")
        .payload(json!({"test": "data"}))
        .build();
    
    publisher.publish(message).await.unwrap();
    
    // 验证订阅者API
    let subscriber = bus.create_subscriber("test-subscriber", "test.*").await.unwrap();
    
    println!("    ✓ rustcloud-bus API兼容性验证通过");
}

async fn test_stream_api_compatibility() {
    println!("  📋 验证rustcloud-stream API兼容性...");
    
    let bus = Arc::new(InMemoryMessageBus::new().await.unwrap());
    
    // 验证流数据源API
    let mut source = BusStreamSource::with_defaults(bus.clone(), "events.*").await.unwrap();
    source.start().await.unwrap();
    
    // 验证流数据汇API
    let mut sink = BusStreamSink::with_defaults(bus.clone(), "output.events").await.unwrap();
    
    // 验证处理器API
    let _map_processor = MapProcessor::with_mapper(|msg| {
        let mut message = msg;
        let mut payload = message.payload().clone();
        payload["processed"] = json!(true);
        message.set_payload(payload);
        message
    });
    
    let _filter_processor = FilterProcessor::with_predicate(|msg| {
        msg.payload().get("active").and_then(|v| v.as_bool()).unwrap_or(true)
    });
    
    source.stop().await.unwrap();
    sink.close().await.unwrap();
    
    println!("    ✓ rustcloud-stream API兼容性验证通过");
}

async fn test_admin_api_compatibility() {
    println!("  📋 验证rustcloud-admin API兼容性...");
    
    let registry = Arc::new(InMemoryRegistry::new());
    
    // 验证服务发现API
    let _service_discovery = ServiceDiscovery::new(
        "test-discovery".to_string(),
        registry.clone(),
        Duration::from_secs(30),
    );
    
    // 验证负载均衡配置API
    let _lb_config = LoadBalancerConfig {
        strategy: "round_robin".to_string(),
        health_check_enabled: true,
        health_check_interval: Duration::from_secs(30),
        max_failures: 3,
        recovery_timeout: Duration::from_secs(60),
    };
    
    println!("    ✓ rustcloud-admin API兼容性验证通过");
}

/// 测试API签名的向后兼容性
/// 确保重构后的API签名与之前版本兼容
#[tokio::test]
async fn test_api_signature_compatibility() {
    println!("🔍 验证API签名向后兼容性...");
    
    // 验证核心trait签名
    trait TestServiceRegistry: Send + Sync {
        fn register(&self, instance: ServiceInstance) -> impl std::future::Future<Output = Result<(), Box<dyn std::error::Error + Send + Sync>>> + Send;
        fn discover(&self, service_name: &str) -> impl std::future::Future<Output = Result<Vec<ServiceInstance>, Box<dyn std::error::Error + Send + Sync>>> + Send;
        fn deregister(&self, instance: &ServiceInstance) -> impl std::future::Future<Output = Result<(), Box<dyn std::error::Error + Send + Sync>>> + Send;
    }
    
    // 验证负载均衡trait签名
    trait TestLoadBalancer: Send + Sync {
        fn select(&self, instances: &[ServiceInstance]) -> Option<ServiceInstance>;
    }
    
    println!("  ✓ 核心trait签名兼容性验证通过");
    println!("✅ API签名向后兼容性验证通过！");
}

/// 验证配置结构的兼容性
#[tokio::test]
async fn test_configuration_compatibility() {
    println!("🔍 验证配置结构兼容性...");
    
    // 验证重试配置结构
    let retry_config = RetryConfig {
        max_attempts: 3,
        timeout: Duration::from_secs(5),
        backoff: BackoffStrategy::Exponential {
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(5),
            multiplier: 2.0,
        },
        retry_conditions: vec!["TIMEOUT".to_string()],
        budget_percent: 10.0,
        jitter_enabled: true,
    };
    
    assert_eq!(retry_config.max_attempts, 3);
    assert_eq!(retry_config.timeout, Duration::from_secs(5));
    
    // 验证熔断器配置结构
    let circuit_config = CircuitBreakerConfig {
        failure_threshold: 5,
        success_threshold: 3,
        timeout: Duration::from_secs(10),
        monitoring_period: Duration::from_secs(60),
    };
    
    assert_eq!(circuit_config.failure_threshold, 5);
    assert_eq!(circuit_config.success_threshold, 3);
    
    println!("✅ 配置结构兼容性验证通过！");
}